package com.config;

import org.devefx.validator.Validator;
import org.devefx.validator.ValidatorConfig;
import org.devefx.validator.ValidatorFactory;
import org.devefx.validator.external.spring.SpringValidationFactory;
import org.devefx.validator.internal.engine.DefaultInvalidHandler;
import org.devefx.validator.internal.engine.ValidatorFactoryImpl;
import org.devefx.validator.spring.ConfigPostProcessor;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;

import java.util.Properties;



//*********************数据验证 configuration************
@Configuration
@ComponentScan(basePackages = {"com.validation"} , includeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM ,value = org.devefx.validator.spring.filter.ValidationScriptMappingTypeFilter.class) })
public class WebValidatorConfig {

    @Bean
    public DefaultInvalidHandler defaultInvalidHandler() {
        DefaultInvalidHandler defaultInvalidHandler = new DefaultInvalidHandler();
        defaultInvalidHandler.setOutputStyle( DefaultInvalidHandler.OutputStyle.XML );
        return defaultInvalidHandler;
    }

    //    创建Validator配置
    @Bean
    public ValidatorConfig validatorConfig(DefaultInvalidHandler defaultInvalidHandler) {
        ValidatorConfig validatorConfig = new ValidatorConfig();
        Properties properties = new Properties();
        validatorConfig.setInvalidHandler( defaultInvalidHandler );
        return validatorConfig;
    }


    @Bean
    public SpringValidationFactory springValidationFactory() {
        return new SpringValidationFactory();
    }

    //验证器工厂
    @Bean
    public ValidatorFactory validatorFactory(ValidatorConfig validatorConfig, SpringValidationFactory springValidationFactory) {
        ValidatorFactoryImpl validatorFactory = new ValidatorFactoryImpl();
        //        Validator配置
        validatorFactory.setValidatorConfig( validatorConfig );
        //        Validation对象Spring容器获取
        validatorFactory.setValidationFactory( springValidationFactory );
        return validatorFactory;
    }

    @Bean
    public Validator validator(ValidatorFactory validatorFactory){
        return  validatorFactory.buildValidator();
    }


    //验证器
    @Bean
    public MethodInvokingFactoryBean methodInvokingFactoryBean(Validator validator ) {
        MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
        methodInvokingFactoryBean.setStaticMethod( "org.devefx.validator.ValidatorUtils.setValidator" );
        methodInvokingFactoryBean.setArguments(validator);
        return methodInvokingFactoryBean;
    }
    //validator自动配置
    @Bean
    public ConfigPostProcessor configPostProcessor(){
        return  new ConfigPostProcessor();
    }

}
